<template>
  <div class="app" v-loading="isLoading">
    <div class="online">在线: {{ onlineList.length }}</div>
    <template v-if="!isLoading">
      <div class="message-list">
        <div class="message-box" id="message_box">
          <template v-for="item in messageList" :key="item.id">
            <template v-if="item.type == 'text'">
              <div
                class="message-item"
                :class="
                  item.from.user_id == userInfo.user_id ? 'message-mine' : ''
                "
              >
                <div class="message-head">
                  <img
                    :src="item.from.user_head"
                    @error="item.from.user_head = noHeadImage"
                  />
                </div>
                <div class="message-content">
                  <div class="message-name">{{ item.from.user_name }}</div>
                  <div
                    class="message-text"
                    :class="
                      userInfo.user_sex == 1 ? 'message-boy' : 'message-girl'
                    "
                  >
                    {{ item.msg }}
                  </div>
                </div>
              </div>
            </template>
            <template v-if="item.type == 'addsong'">
              <div class="system addsong">
                <div class="msg">
                  <span class="user">{{ item.song.user.user_name }}</span>
                  点了一首
                  <span class="song">{{ item.song.name }}</span>
                </div>
              </div>
            </template>
          </template>
        </div>
        <div class="controll">
          <div class="item" @click="openSearchSong">
            <i class="iconfont icon-icon_search"></i>
            搜索点歌
          </div>
          <div class="item" @click="openSongList">
            <i
              class="iconfont icon-changyongtubiao-xianxingdaochu-zhuanqu-18"
            ></i>
            已点歌曲
          </div>
        </div>
      </div>
      <div class="message-form">
        <textarea
          :placeholder="placeholder"
          v-model="message"
          @keydown="messageKeyDown"
        ></textarea>
      </div>
      <div class="form-password" v-if="showPasswordForm"></div>
    </template>
  </div>
</template>

<script>
export default {
  data() {
    return {
      room: false,
      noHeadImage: require("@/asset/img/head.jpg"),
      isLoading: false,
      showPasswordForm: false,
      onlineList: [],
      placeholder: "说点什么吧...",
      message: "",
      messageList: [],
      userInfo: false,
      lock: false,
    };
  },
  watch: {
    "$store.state.nowApp.data.room_id"() {
      if (
        this.$store.state.nowApp.key === "room_main" &&
        this.$store.state.nowApp.data.room_id !== this.room.room_id
      ) {
        this.room = JSON.parse(JSON.stringify(this.$store.state.nowApp.data));
        this.joinRoom();
      }
    },
    "$store.state.messageList": {
      handler(messageList) {
        messageList = messageList.filter((item) => {
          return item.type == "room" && item.room == this.room.room_id;
        });
        this.messageList = JSON.parse(
          JSON.stringify(
            messageList.map((item) => {
              return item.message;
            })
          )
        );
        this.autoScroll();
      },
      immediate: true,
      deep: true,
    },
    "$store.state.onlineList": {
      handler(onlineList) {
        this.onlineList = onlineList;
      },
      immediate: true,
      deep: true,
    },
  },
  created() {
    this.room = JSON.parse(JSON.stringify(this.$store.state.nowApp.data));
    this.joinRoom();
    let userInfo = localStorage.getItem("user");
    if (userInfo) {
      this.userInfo = JSON.parse(userInfo);
    }
  },
  methods: {
    openSearchSong() {
      this.$store.commit("openAppByKey", "song_search");
    },
    openSongList() {
      this.$store.commit("openAppByKey", "room_song");
    },
    autoScroll() {
      if (!this.lock) {
        this.$nextTick(() => {
          let ele = document.getElementById("message_box");
          ele.scrollTop = ele.scrollHeight;
        });
      }
    },
    /**
     * 加载本地消息记录
     */
    getLocalMessageList() {
      this.messageList = [];
      this.autoScroll();
    },
    /**
     * 进入房间
     */
    joinRoom() {
      this.isLoading = true;
      this.$emit("api", {
        event: "setWindowTitle",
        title: "正在进入,请稍候...",
      });
      this.request({
        url: "room/join",
        method: "POST",
        data: {
          room_id: this.room.room_id,
          password: this.password,
        },
        success: (res) => {
          this.$store.commit("updateRoom", this.room);
          this.$emit("api", {
            event: "sendWssMessage",
            data: res.data.key,
          });
          this.$emit("api", {
            event: "setWindowTitle",
            title: this.room.room_name + "(" + this.room.room_id + ")",
          });
          this.getLocalMessageList();
        },
        error: (res) => {
          switch (res.code) {
            case this.config.httpStatusCode.FORBIDDEN: {
              this.showPasswordForm = true;
              break;
            }
            default: {
              let app = this.tool.getAppByKey("room_main");
              app.hideWhenClose = false;
              this.$store.commit("closeApp", app);
            }
          }
        },
        final: () => {
          this.isLoading = false;
        },
      });
    },
    /**
     * 输入框键盘按下事件
     */
    messageKeyDown(e) {
      // console.log(e.ctrlKey, e.key);
      switch (e.key) {
        case "Enter":
          e.preventDefault();
          this.sendMessage(this.message);
          break;
      }
    },
    /**
     * 发送消息
     */
    sendMessage(message) {
      let sendData = {
        type: "text",
        msg: message,
        at: false,
      };
      this.message = "";
      this.request({
        url: "room/send",
        method: "POST",
        data: sendData,
        success: () => {},
        error: () => {
          this.message = message;
        },
      });
    },
  },
};
</script>
<style scoped lang="scss">
.app {
  display: flex;
  flex: 1;
  width: 100%;
  color: #333;
  text-shadow: none;
  flex-direction: column;
  .online {
    position: absolute;
    right: 15px;
    top: 13px;
    color: yellow;
    font-size: 12px;
  }
  .message-list {
    flex: 1;
    height: 0;
    background-color: #eee;
    display: flex;
    flex-direction: column;
    position: relative;
    .message-box {
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      bottom: 30px;
      overflow: hidden;
      overflow-y: auto;
      .message-item {
        display: flex;
        flex-direction: row;
        margin: 10px;
        .message-head {
          width: 40px;
          height: 40px;
          border-radius: 8px;
          overflow: hidden;
          cursor: pointer;
          img {
            width: 100%;
            height: 100%;
          }
        }

        .message-head:hover {
          animation: userHeadHoverAnimation 0.5s linear 1;
          transform-origin: center bottom;
        }
        .message-content {
          flex: 1;
          text-align: left;
          .message-name {
            font-size: 16px;
            margin: 0px 15px;
          }
          .message-text {
            background-color: #ccc;
            display: inline-block;
            padding: 8px 16px;
            border-radius: 8px;
            margin: 10px 15px 20px 15px;
            color: #333;
            font-size: 12px;
            position: relative;
            max-width: 40%;
            word-break: break-all;
            text-align: left;
          }
        }
      }
      .message-mine {
        flex-direction: row-reverse;
        .message-content {
          text-align: right;
        }
        .message-text::after {
          content: "";
          position: absolute;
          right: -15px;
          top: -6px;
          left: calc(100%);
          width: 10px;
          height: 15px;
          border: 0 solid transparent;
          border-bottom-width: 10px;
          border-bottom-color: currentColor;
          border-radius: 0 0 20px 0;
        }
        .message-boy {
          background-color: #66cbff !important;
          color: white !important;
        }
        .message-boy::after {
          color: #66cbff !important;
        }
        .message-girl {
          background-color: #fe9898 !important;
          color: white !important;
        }
        .message-girl::after {
          color: #fe9898 !important;
        }
      }

      .system {
        text-align: center;
        padding: 5px 10%;
        color: #999;
        font-size: 12px;
        .msg {
          display: inline-block;
          padding: 2px 10px;
          border-radius: 5px;
          color: #aaa;
          background: #ddd;
          .user {
            cursor: pointer;
            color: #666;
          }
          .user:hover {
            color: #ff4500;
          }
        }
      }
    }
    .controll {
      display: flex;
      flex-direction: row;
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      padding: 5px;
      background-color: #eee;
      .item {
        border: 1px solid #eee;
        display: inline-block;
        padding: 5px 10px;
        margin: 0px 2px;
        font-size: 12px;
        vertical-align: middle;
        color: #aaa;
        border-radius: 8px;
        background-color: #e5e5e5;
        text-align: center;
        width: 70px;
        cursor: pointer;
        transition: all 0.5s;
        .iconfont {
          font-size: 16px;
        }
      }
      .item:hover {
        color: #333;
        background-color: #ccc;
      }
    }
  }
  .message-form {
    height: 80px;
    background-color: #eee;
    border-top: 1px solid #ddd;
    padding: 10px 15px;
    textarea {
      border: none;
      width: 100%;
      height: 100%;
      resize: none;
      outline: none;
      background-color: transparent;
    }
  }
}
</style>